#include "includes.h"
//ISR(SPI_STC_vect)
//{

//}

void SPI_MasterInit(void)
{
	/* Set MOSI(PB5), SS(PB4), SCK(PB7) and MCP_CS(chosen to PB3) output, all others input */
	DDRB = (1<<DDB5)|(1<<DDB4)|(1<<DDB7)|(1<<DDB3);
	
	// Sets the SS and MCP_CS inactive
	disable_spi_transmission(BUTTERFLY);
	disable_spi_transmission(MCP);

	/* Enable SPI, Master, set clock rate fck/128 */
	SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPR1);//|(1<<SPIE);
}

void enable_spi_transmission(uint8_t slave)
{
	clear_bit(PORTB, slave);
}

void disable_spi_transmission(uint8_t slave)
{
	set_bit(PORTB, slave);
}


uint8_t SPI_read()
{
	return (uint8_t) SPDR;
}


void SPI_write(char cData)
{
	/* Start transmission */
	SPDR = cData;
	/* Wait for transmission complete */
	while(!(SPSR & (1<<SPIF)))
	;
}


void SPI_MasterSend(char string[28]) {
	int i=0;
	cli();
	enable_spi_transmission(BUTTERFLY);
	_delay_ms(20);
	SPI_write(0x01);
	while(string[i]!='\0') {
		SPI_write(string[i]);
		i++;
	}
	SPI_write(string[i]);
	SPI_write(0x02);
	disable_spi_transmission(BUTTERFLY);
	_delay_ms(20);
	sei();
}
